<?php
// +----------------------------------------------------------------------
// | ProjectName : domall
// +----------------------------------------------------------------------
// | Description :  支付
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.idowe.com All rights reserved.
// +----------------------------------------------------------------------
// | Authors : Johhny <chenjf@idowe.com>  Date : 2016-03-08
// +----------------------------------------------------------------------
namespace app\index\controller;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use PHPQRCode\QRcode;

class Pay extends Base
{

    /**
     * 选择支付方式
     * @author Johhny <chenjf@idowe.com>
     */
    public function index(){

        $paysn = $_GET['paysn'];

        $order_where['buyer_id'] = $this->user_info['member_id'];
        $order_where['pay_sn'] = $paysn;
        $order_list = M('orders')->where($order_where)->select();

        $order_amount = 0;
        foreach($order_list as $order_item){
            $order_amount = $order_amount + $order_item['order_amount'];
        }

        $this->assign('order_amount',$order_amount);
        $this->assign('order_list',$order_list);
        return $this->display();
    }

    /**
     * 实际支付
     * @author Johhny <chenjf@idowe.com>
     */
    public function real_order(){
        if(IS_POST){
            $pay_type = $_POST['pay_type'];
            $pay_sn = $_POST['pay_sn'];
            $order_info = M('orders')->where(array('pay_sn'=>$pay_sn))->find();
            if($pay_type == 'weixin'){
                $options = [
                    'debug'     => true,
                    'app_id'    => '',
                    'secret'    => '',
                    'token'     => '',
                    'payment' => [
                        'merchant_id'        => '',
                        'key'                => '',
//                        'cert_path'          => 'apiclient_cert.pem', // XXX: 绝对路径！！！！
//                        'key_path'           => 'apiclient_key.pem',      // XXX: 绝对路径！！！！
                        // ...
                    ],
                ];

                $app = new Application($options);
                $payment = $app->payment;

                $order_amount = $order_info['order_amount']*100;

                $attributes = [
                    'body'             => $order_info['order_sn'],
                    'detail'           => $order_info['order_sn'],
                    'out_trade_no'     => $order_info['order_sn'],
                    'total_fee'        => $order_amount,
                    'notify_url'       => C('web_url').'/index/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type'       => 'NATIVE',
                ];

                $order = new Order($attributes);

                $result = $payment->prepare($order);
                if($result->return_code == "FAIL"){
                    return $this->error($result->return_msg);
                }else{
                    $code_url = urlencode(trim($result->code_url));
                    return $this->success($code_url);
                }
            }
        }
    }

    /**
     * 支付后通知
     * @author Johhny <chenjf@idowe.com>
     */
    public function notify(){
        $options = [
            'debug'     => true,
            'app_id'    => '',
            'secret'    => '',
            'token'     => '',
            'payment' => [
                'merchant_id'        => '',
                'key'                => '',
//                        'cert_path'          => 'apiclient_cert.pem', // XXX: 绝对路径！！！！
//                        'key_path'           => 'apiclient_key.pem',      // XXX: 绝对路径！！！！
            ],
        ];

        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){

            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = M('orders')->where(array('order_sn'=>$notify->out_trade_no))->find();

            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order['api_pay_state'] == 1) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }

            // 用户是否支付成功
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $order['api_pay_time'] = time(); // 更新支付时间为当前时间
                $order['api_pay_state'] = '1';
                $order['payment_code'] = 'wx_saoma';
                $order['trade_no'] = $notify->transaction_id;
            } else { //
                $order['payment_code'] = 'wx_saoma';
                $order['api_pay_time'] = time();
            }

            M('orders')->where(array('order_sn'=>$notify->out_trade_no))->save($order); // 保存订单

            return true; // 返回处理完成
        });

        $this->redirect(url('index/order'));
    }

    /**
     * 生成二维码支付
     * @author Johhny <chenjf@idowe.com>
     */
    public function qrcode(){
        $url = $_GET['url'];
        $url = urldecode(trim($url));
        return QRcode::png($url,false,1,8);
    }
}